<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.keyword" placeholder="用户名" style="width:200px" clearable></el-input>
                </el-form-item>

                <el-select v-model="userState" placeholder="用户状态">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>

                <el-form-item>
                    <el-button type="primary" v-on:click="search" icon="el-icon-search" style="margin-left: 15px;">查询
                    </el-button>
                </el-form-item>

                <el-form-item style="padding-left: 19%;">
                    <el-button type="primary" @click="showAdd" icon="el-icon-plus">新增</el-button>
                </el-form-item>
                <el-form-item style="float:right">
                    <el-upload action="/api/user/addBatch" name="file" :on-success="onSuccess" :on-error="onError">
                        <el-button type="primary" icon="el-icon-plus">批量导入</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="dataList" border highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                  style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="username" label="用户名" width="120">
            </el-table-column>
            <el-table-column prop="email" label="邮箱" min-width="180">
            </el-table-column>

            <el-table-column prop="mobilephone" label="手机" min-width="180">
            </el-table-column>
            <el-table-column prop="state" label="状态" :formatter="formatStatus" min-width="100">
            </el-table-column>

            <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                    <el-button size="mini" @click="showEdit(scope.$index, scope.row)" icon="el-icon-edit">编辑</el-button>
                    <el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)"
                               icon="el-icon-delete">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="total, sizes, prev, pager, next, jumper"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :page-sizes="pageSizes"
                           :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--新增/编辑共用界面-->
        <el-dialog :title="formTitle" :visible.sync="formVisible" :close-on-click-modal="false">
            <el-form :model="formData" label-width="80px" :rules="formRules" ref="formData">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="formData.username" :disabled="action!='add'"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="formData.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobilephone">
                    <el-input v-model="formData.mobilephone"></el-input>
                </el-form-item>

                <el-form-item label="用户类别" prop="category">
                    <el-select v-model="formData.usertype" placeholder="请选择用户类别" @change="usertypechange">
                        <el-option value="2" label="学生">学生</el-option>
                        <el-option value="1" label="教师">教师</el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="系" prop="departmentid" v-show="formData.usertype=='1'">
                    <el-cascader filterable
                                 :options="optionsDepartmentOrClass"
                                 :clearable="true"
                                 :show-all-levels="false"
                                 expand-trigger="hover"
                                 @change="handleChange"
                                 placeholder="请选择系">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="班级" prop="classid" v-show="formData.usertype=='2'">
                    <el-cascader filterable
                                 :options="optionsDepartmentOrClass"
                                 :clearable="true"
                                 :show-all-levels="false"
                                 expand-trigger="hover"
                                 @change="handleChange"
                                 placeholder="请选择班级">
                    </el-cascader>
                </el-form-item>

                <el-form-item label="状态">
                    <el-radio v-model="formData.state" label="1">启用</el-radio>
                    <el-radio v-model="formData.state" label="2">禁用</el-radio>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="formVisible = false">取消</el-button>
                <el-button type="primary" @click.native="saveSubmit" :loading="submitLoading">提交</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>

    export default {
        data() {
            return {
                filters: {
                    keyword: ''
                },

                options: [
                    {
                        value: '0',
                        label: '全部'
                    },
                    {
                        value: '1',
                        label: '启用'
                    },
                    {
                        value: '2',
                        label: '禁用'
                    }
                ],
                optionsDepartmentOrClass:[],

                listLoading: false, //是否显示加载动画
                submitLoading: false,

                dataList: [], //数据列表(用户)

                total: 0,
                pageIndex: 1, //页码
                pageSize: this.CONSTANT.PAGE_SIZE, //分页大小
                pageSizes: this.CONSTANT.PAGE_SIZES, //分页大小选择列表

                sels: [],//列表选中列

                action: '', // 'add'-添加，'edit'-编辑，'detail'-详情
                formVisible: false, //界面是否显示
                formTitle: '', //界面标题
                formRules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'}
                    ],
                    mobilephone:[{validator:(rule,value,callback)=>{

                        let reg=/^1[3|4|5|8][0-9]\d{4,8}$/;

                        if(reg.test(value) == false&&value){
                            callback(new Error("手机号格式不正确"));
                        }
                    }, trigger:'blur'}],
                    usertype:[{required:true,message:"请选择用户类别",trigger:'blur'}]
                },

                //新增/编辑界面数据
                formData: {
                    username: '',
                    email: '',
                    mobilephone: '',
                    state:'1',
                    usertype:'',
                    departmentid:'',
                    classid:''
                },

                userState: "" //用户状态

            }
        },
        methods: {
            selsChange: function (sels) { //保存复选框选中的记录
                this.sels = sels;
            },
            handleChange:function (value) {
                if(this.formData.usertype == 1){
                    this.formData.departmentid = value[value.length-1];
                } else {
                    this.formData.classid = value[value.length-1];
                }
            },
            handleReset() {
                this.filters.keyword = "";
                this.userState = "";
            },
            handleSizeChange(val) { //改变分页大小
                this.pageSize = val;
                this.getDataList();
            },
            handleCurrentChange(val) { //页码跳转
                this.pageIndex = val;
                this.getDataList();
            },
            search() {
                this.getDataList();
            },
            //用户状态显示转换
            formatStatus: function (row, column) {
                return row.state == 1 ? '启用' : row.state == 2 ? '禁用' : '未知';
            },
            usertypechange(value){
                console.log(value);
                if(value==1){
                    this.getDepartmentOrClassTree(3);
                }else if(value==2){
                    this.getDepartmentOrClassTree(5);
                }
            },
            getDataList() { //获取数据列表（用户）

                this.listLoading = true;

                let para = {
                    pageIndex: this.pageIndex,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword,
                    state: this.userState
                };

                this.$http.post('/api/user/findBatchByCondition', para).then(res => {

                    this.listLoading = false;

                    this.total = res.data.total;
                    this.dataList = res.data.data;

                }).catch((error) => {
                    this.listLoading = false;
                    if (error) console.log(error);
                });
            },
            getDepartmentOrClassTree(rank){
                this.$http.get("/api/school/getSchoolMajorClassTree/"+rank).then((res) => {
                    this.optionsDepartmentOrClass = res.data.data;
                }).catch((error) => {
                    console.log(error);
                });
            },
            handleDel: function (index, row) { //删除
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    let para = {id: row.id};
                    this.$http.get('/api/user/remove/' + para.id).then((res) => {

                        if (res.data.code == 0) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }
                        this.getDataList();
                    });
                }).catch(() => {
                    if (error) console.log(error);
                });
            },
            showAdd: function () { //显示新增界面

                this.formVisible = true;
                this.formData = {
                    username: '',
                    email: '',
                    mobilephone: '',
                    state:'1',
                    departmentid:'',
                    classid:''
                };

                this.action = "add";
                this.formTitle = '新增';
            },
            onSuccess:function (response,file) {
                console.log(response);
                console.log("文件上传成功");
            },
            onError:function () {
              console.log("文件上传失败");
            },
            showEdit: function (index, row) { //显示编辑界面

                this.formVisible = true;
                this.formData = Object.assign({}, row);

                this.formData.usertype=this.formData.usertype+'';
                this.formData.state=this.formData.state+''; //转成string

                this.action = "edit";
                this.formTitle = '编辑';
                console.log(this.formData);
            },
            saveSubmit: function () { //保存：新增/编辑
                let apiPath = '';
                if (this.action == 'add') {
                    apiPath = '/api/user/add';
                } else {
                    apiPath = '/api/user/modify';
                }

                this.$confirm('确认提交吗？', '提示', {}).then(() => {
                    this.submitLoading = true;
                    let para = {};
                    let user = {
                        id:this.formData.id,
                        username: this.formData.username,
                        email: this.formData.email,
                        mobilephone: this.formData.mobilephone,
                        state:'1',
                        usertype:this.formData.usertype
                    };
                    if(this.formData.usertype == 1){
                        para = {
                            user: user,
                            teacherInfo:{
                                departmentid:this.formData.departmentid
                            }
                        };
                    }
                    if(this.formData.usertype==2){
                        para = {
                            user: user,
                            studentInfo:{
                                classid:this.formData.classid
                            }
                        };
                    }
                    console.log(para);


                    // this.$http.post(apiPath, para).then(res => {
                    //     this.submitLoading = false;
                    //
                    //     if (res.data.code == 0) {
                    //         this.$message({
                    //             message: '提交成功',
                    //             type: 'success'
                    //         });
                    //         this.$refs['formData'].resetFields();
                    //         this.formVisible = false;
                    //         this.getDataList(); //重新加载数据
                    //     } else {
                    //         this.$message({
                    //             message: '提交失败',
                    //             type: 'error'
                    //         });
                    //     }
                    // }).catch((error) => {
                    //     this.submitLoading = false;
                    //     if (error) console.log(error);
                    // });
                });
            },
            batchRemove: function () { //批量删除
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    let para = {ids: ids};
                    this.$http.get('/api/user/removeBatch/' + para.ids).then((res) => {

                        if (res.data.code == 0) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }

                        this.getDataList();
                    });
                }).catch(() => {
                    if (error) console.log(error);
                });
            }
        },
        mounted() {
            this.getDataList(); //进入页面就加载数据
            // switch (this.)
        }
    }

</script>
